package com.ruoyi.scheduler;

import com.alibaba.druid.support.json.JSONUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.ruoyi.domain.MaterielThree;
import com.ruoyi.mapper.MaterielThreeMapper;
import com.ruoyi.utils.CustomSnakeCaseToCamelCaseStrategy;
import com.ruoyi.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MaterielThreeSchedulerService {

    @Autowired
    MaterielThreeMapper materielThreeMapper;

    @Value("${scheduler.enabled:true}")
    private boolean schedulerEnabled;
    public String getMaterielThree() {
        String url = "http://192.168.3.35:9990/CROSS/RESTful"; // 第三方API的URL

        // 请求头信息
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("digi-key", "1BFA1C0436F4D2EE8ECF09B6B936EB4F");
        headers.put("digi-host", "{\"ver\":\"5.7\",\"prod\":\"YMES\",\"timezone\":\"+8\",\"ip\":\"192.168.3.35\",\"id\":\"\",\"lang\":\"zh_CN\",\"acct\":\"dcms\",\"timestamp\":\"2018071990007275\"}");
        headers.put("digi-service", "{\"prod\":\"E10\",\"ip\":\"192.168.3.35\",\"name\":\"ymes.purchase_arrival.query\",\"id\":\"DemoCompany_External\"}");
        headers.put("digi-data-exchange-protocol", "1.0");
        headers.put("digi-type", "sync");

        //请求体信息
        String requestBody = "{\n" +
                "  \"std_data\": {\n" +
                "    \"parameter\": {\n" +
                "      \"pageSize\": 5000,\n" +
                "      \"pageNo\": 1,\n" +
                "      \"isGetSchema\": false,\n" +
                "      \"isGetCount\": false,\n" +
                "      \"conditions\": [],\n" +
                "      \"orders\": []\n" +
                "    }\n" +
                "  }\n" +
                "}\n";
        String response = null;
        try {
            // 调用Get请求
            //String response = HttpUtils.sendGet(url, headers);


            // 调用Post请求
            response = HttpUtils.sendPost(url, headers, requestBody);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


    public List<MaterielThree> listMaterielThree() throws JsonProcessingException {
        //处理接口数据
        String jsonOne = StringUtils.substringAfter(getMaterielThree(), "[");
        String jsonTwo = StringUtils.substringBefore(jsonOne, "]");
        String jsonStr = "["+jsonTwo+"]";
        ObjectMapper mapper = new ObjectMapper();

        mapper.setPropertyNamingStrategy(new CustomSnakeCaseToCamelCaseStrategy());

        List<MaterielThree> materielThrees = mapper.readValue(jsonStr, new TypeReference<List<MaterielThree>>() {});

        for (MaterielThree materielThree : materielThrees) {
            if (materielThree.getDocDate() != null && !materielThree.getDocDate().isEmpty()) {
                materielThree.setDocDate(materielThree.getDocDate().substring(0, 10));
            }
            // 对其他日期字段也添加null检查
            if (materielThree.getCreateDate() != null && !materielThree.getCreateDate().isEmpty()) {
                materielThree.setCreateDate(materielThree.getCreateDate().substring(0, 10));
            }
            if (materielThree.getLastModifiedDate() != null && !materielThree.getLastModifiedDate().isEmpty()) {
                materielThree.setLastModifiedDate(materielThree.getLastModifiedDate().substring(0, 10));
            }
        }
        return materielThrees;
    }


    //@Scheduled(fixedRate = 60000) // 每分钟执行一次
    @Scheduled(fixedRate = 3600000) // 每小时执行一次
    //@Scheduled(fixedRate = 86400000) // 每天执行一次
    @Transactional
    public void scheduleTask() {
        // 判断是否启用定时任务
        if (!schedulerEnabled || java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("jdwp")) {
            return;
        }
        try {
            List<MaterielThree> materielThreeList1 = materielThreeMapper.selectAll();
            List<MaterielThree> materielThreeList2 = listMaterielThree();
            List<MaterielThree> list = uniqueListThree(materielThreeList2, materielThreeList1);
            for(MaterielThree materielThree : list) {
                materielThreeMapper.insertMaterielThree(materielThree);
            }
        } catch (JsonProcessingException e) {
            // 记录日志或处理异常
            e.printStackTrace();
        } catch (Exception e) {
            // 处理其他可能的异常
            e.printStackTrace();
        }
    }
    private List<MaterielThree> uniqueListThree(List<MaterielThree> source,List<MaterielThree> target){
        if(CollectionUtils.isEmpty(source)){
            return List.of();
        }
        if(CollectionUtils.isEmpty(target)){
            return source;
        }
        return source.stream()
                .filter(sc -> target.stream().noneMatch(ta ->
                        sc != null && ta != null  &&
                            /*    Objects.equals(sc.getDocDate(), ta.getDocDate()) &&
                                Objects.equals(sc.getDocNo(), ta.getDocNo()) &&
                                Objects.equals(sc.getItemCode(), ta.getItemCode()) &&
                                Objects.equals(sc.getItemDescription(), ta.getItemDescription()) &&
                                Objects.equals(sc.getItemSpecification(), ta.getItemSpecification()) &&
                                Objects.equals(sc.getLotCode(), ta.getLotCode()) &&
                                Objects.equals(sc.getLotDescription(),ta.getLotDescription()) &&
                                Objects.equals(sc.getSupplierFullName(),ta.getSupplierFullName()) &&
                                Objects.equals(sc.getSupplierName(),ta.getSupplierName()) &&
                                Objects.equals(sc.getSupplierCode(),ta.getSupplierCode()) &&
                                Objects.equals(sc.getBusinessQty(),ta.getBusinessQty()) &&
                                Objects.equals(sc.getPieces(),ta.getPieces()) &&
                                Objects.equals(sc.getCreateDate(),ta.getCreateDate()) &&
                                Objects.equals(sc.getArrivalDate(),ta.getArrivalDate()) &&
                                Objects.equals(sc.getEmployeeName(),ta.getEmployeeName()) &&
                                Objects.equals(sc.getLastModifiedDate(),ta.getLastModifiedDate()) &&
                                Objects.equals(sc.getRemark(),ta.getRemark()) &&
                                Objects.equals(sc.getEmployeeName1(),ta.getEmployeeName1())*/
                                Objects.equals(sc.getDocNo(), ta.getDocNo()) &&
                                Objects.equals(sc.getItemCode(), ta.getItemCode()) &&
                                Objects.equals(sc.getLotCode(), ta.getLotCode()) &&
                                Objects.equals(sc.getSupplierCode(), ta.getSupplierCode()) &&
                                Objects.equals(sc.getRemark(),ta.getRemark()) &&
                                Objects.equals(sc.getDocDate(), ta.getDocDate())
                ))
                .collect(Collectors.toList());
    }

}
